import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Axios from 'axios'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

let n = 0;

let url = "/prod-api/openid/login?next="
let url2 = ""
const mode = process.env.VUE_APP_MODE
console.log('Mode:', mode)

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  if (window.location.hash !== "" && window.location.hash !== "#/" && window.location.hash !== "#/dashboard") {
    url = url + encodeURIComponent(window.location.hash)
  }

  var pn = decodeURIComponent(window.location.pathname)
  if (pn !== "" && pn !== "/" && pn !== "/dashboard") {
      url2 = pn
  }

  // set page title
  document.title = getPageTitle(to.meta.title)


  // determine whether the user has logged in
  const hasToken = getToken()
  // console.log(hasToken)

  const urlParams = new URLSearchParams(window.location.search);
  const jsonDataParam = urlParams.get('data');
  // console.log(jsonDataParam)

  // 设置成功后，你可能想要移除 URL 参数，以防用户刷新页面时再次执行这个逻辑
  const urlWithoutDataParam = window.location.origin + window.location.pathname;
  window.history.replaceState({}, document.title, urlWithoutDataParam);



  if (hasToken) {
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
        NProgress.done()
      } else {
        const hasGetUserInfo = store.getters.name
        if (hasGetUserInfo) {
          next()
        } else {
          try {
            // get user info
            await store.dispatch('user/getInfo')
            next()
          } catch (error) {
            // remove token and go to login page to re-login
            await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        }
    }

  } else {
    /* has no token*/
    if (mode === "debug") {
      // debug环境
      if (whiteList.indexOf(to.path) !== -1) {
        // console.log(to.path)
        // in the free login whitelist, go directly
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        // const loginRedirectURL = 'http://localhost:8080/prod-api/openid/login'
        // next(`/login?redirect=${encodeURIComponent(loginRedirectURL)}`)
        next(`/login?redirect=${to.path}`)
        // window.location.href = url;
        // window.location.href = '/prod-api/openid/login';
        NProgress.done()
      }
    } else {
      //生产环境
      if (jsonDataParam) {
        // console.log("setToken")
        n += 1;
        try {
          // 解析 JSON 数据
          const jsonData = JSON.parse(decodeURIComponent(jsonDataParam));
          // console.log(jsonData)

          // 提取 token 字段
          const token = jsonData.token;
          // console.log(token)

          if (token) {
            // 使用你的 setToken 函数将 token 设置到 Cookie 中
            setToken(token);

            // 设置成功后，你可能想要移除 URL 参数，以防用户刷新页面时再次执行这个逻辑
            // const urlWithoutDataParam = window.location.origin + window.location.pathname;
            // window.history.replaceState({}, document.title, urlWithoutDataParam);
            // router.replace('/')
          }
        } catch (error) {
          console.error('Error parsing JSON data:', error);
          // 解析错误时，跳转到登录页
          next('/prod-api/openid/login');
        }
      }

      // console.log(n);
      if (n === 0) {
        window.location.href = url;
        // window.location.href = '/prod-api/openid/login';
        // next(`/login?redirect=${to.path}`)
      } else {
        window.location.href = url2
        // console.log(window.location.href)
        // location.reload();
      }
      NProgress.done();
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
